package com.yishusmt.mobsmt.advice;

import com.yishusmt.mobsmt.dto.base.ErrorBase;
import com.yishusmt.mobsmt.dto.base.Result;
import com.yishusmt.mobsmt.enums.ResultCodeEnum;
import com.yishusmt.mobsmt.utils.DateUtil;
import com.yishusmt.mobsmt.utils.JacksonUtil;
import io.swagger.models.Model;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 增强Controller
 *
 * @author zhangyi
 * @date 2018/8/8 11:03
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalControllerAdvice implements ResponseBodyAdvice {

    private ThreadLocal<Object> modelHolder = new ThreadLocal<>();

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleIllegalParamException(MethodArgumentNotValidException e, HttpServletRequest request) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String tips = "参数不合法";
        if (errors.size() > 0) {
            tips = errors.get(0).getDefaultMessage();
        }
        log.error(tips, e);
        return new Result(ResultCodeEnum.REQUEST_PARAM_ERROR, tips);
    }

    @ExceptionHandler(HandleException.class)
    public ErrorBase<String> myError(Exception e,HttpServletRequest request){
        ErrorBase<String> errorBase = new ErrorBase<>();
        errorBase.setCode(ErrorBase.ERROR_CODE);
        errorBase.setMessage(e.getMessage());
        errorBase.setCurrentTime(DateUtil.getLocalDate());

        return errorBase;
    }
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        // ModelHolder 初始化
        modelHolder.set(webDataBinder.getTarget());
    }


    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        modelHolder.remove();
        return null;
    }
}
